package cn.kzgg.ymcc.consumer;

import cn.kzgg.ymcc.domain.MessageSms;
import cn.kzgg.ymcc.dto.MessageSmsDto;
import cn.kzgg.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-smsmessage-consumer",
        topic = "msg-topic",
        selectorExpression = "msg-tags"
)
@Slf4j
public class MsgConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0) {
            return;
        }
        String msgJsonStr = new String(body, StandardCharsets.UTF_8);
        MessageSmsDto messageSmsDto = JSON.parseObject(msgJsonStr, MessageSmsDto.class);

        savemessageSmsDto(messageSmsDto);
        log.info("消息发送成功" + messageSmsDto.getTitle());

    }

    private void savemessageSmsDto(MessageSmsDto messageSmsDto) {
        Date date = new Date();
        messageSmsDto.getUsers().forEach(userSmsDto -> {
                    MessageSms messageSms = new MessageSms();
                    BeanUtils.copyProperties(messageSmsDto, messageSms);
                    messageSms.setUserId(userSmsDto.getId());
                    messageSms.setSendTime(date);
                    messageSmsService.insert(messageSms);

                }
        );
    }
}
